package LoginUtil;

import java.io.IOException;
import java.sql.*;
import java.util.*;

import com.db4o.*;
import com.db4o.config.EmbeddedConfiguration;
import com.db4o.config.annotations.reflect.Db4oConfigurator;
import com.db4o.cs.Db4oClientServer;
import com.db4o.cs.config.ServerConfiguration;
import com.db4o.ext.InvalidPasswordException;
import com.db4o.reflect.jdk.JdkReflector;

public class ConnectionManager implements Runnable {

	/**
	 * Path to the database file
	 */
	public final static String DB4OFILENAME = "MedsysDB.data";
	/**
	 * Port the server is listening at
	 */
	public static final int PORT = 7777;
	
	/**
	 * Holds the ObjectServer with a connection persistently open
	 */
	private static ObjectServer server;
	
	/**
	 * Flag to stop the server
	 */
	private static boolean stop;
	
	/**
	 * Gets an ObjectContainer to execute queries on.  Will connect to the server if not already
	 * @return
	 */
	public static ObjectContainer getObjectContainer() {
		if(server == null) startServer();
		return server.openClient();
	}
	
	/**
	 * Gets an ObjectContainer to execute queries on.  Will throw an InvalidPasswordException if the password is incorrect or null
	 * @param username
	 * @param password
	 * @return
	 */
	public static ObjectContainer getObjectContainer(String username, String password) 
					throws InvalidPasswordException {
		if(server == null) startServer();
		return server.openClient();
	}
	
	
	/**
	 * Establishes the initial connection to the server.  Note that 
	 * the program never disconnects or closes the server.  Possible design flaw?
	 */
   public static void startServer() {
	   Thread s = new Thread(new ConnectionManager(), "server");
	    s.start();
	    s.setPriority(Thread.MAX_PRIORITY);
	}
   
   public static void stopServer() {
	   stop = true;
   }
   
   public static void authenticateUser(String username, String password) {
	   server.grantAccess(username, password);
   }

   @Override
   public void run() {
	   	synchronized(this) {
	   		ServerConfiguration config = Db4oClientServer.newServerConfiguration();
	   		config.common().reflectWith(new JdkReflector(Thread.currentThread().getContextClassLoader()));
	   		server = Db4oClientServer.openServer(config, DB4OFILENAME, PORT);
	   		initialAuth();
	   		
	   		try
			{	    
	   			// print heartbeat message every minute
				while(!stop) {
					System.out.println("SERVER:[" + System.currentTimeMillis() + 
							"] Server is running. \n");
					this.wait(60000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				server.close();
			}
	   	}
   	
   }
   
   /** 
    * Does initial user authentication for debugging purposes
    */
   private void initialAuth() {
	   server.grantAccess("admin", "admin");
   }

   
   // code beyond this point is only relevant if using a RDBMS
   static Connection con;
   static String url;
         
   public static Connection getConnection()
   {
     
      try
      {
         String url = "jdbc:odbc:" + "DataSource"; 
         // assuming "DataSource" is your DataSource name

         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         
         try
         {            	
            con = DriverManager.getConnection(url,"username","password"); 
             								
         // assuming your SQL Server's	username is "username"               
         // and password is "password"
              
         }
         
         catch (SQLException ex)
         {
            ex.printStackTrace();
         }
      }

      catch(ClassNotFoundException e)
      {
         System.out.println(e);
      }

   return con;
}



}